package de.uni_saarland.coli.doclists.index.docmentmanager;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import de.uni_saarland.coli.doclists.data.btree.MemoryMapData;
import de.uni_saarland.coli.doclists.document.ITextDocument;
import de.uni_saarland.coli.doclists.document.IndexDocument;
import de.uni_saarland.coli.doclists.document.iterator.IDocumentIterator;
import de.uni_saarland.coli.doclists.index.IDiscIO;
import de.uni_saarland.coli.doclists.index.Index;
import de.uni_saarland.coli.doclists.texttools.ITextTokenizer;

public class MemoryDocumentManager implements IDocumentManager, IDiscIO,
		Serializable {

	/**
	 * Serial Version UID
	 */
	private static final long serialVersionUID = 5011724618227231448L;

	private MemoryMapData<IndexDocument> docMap;
	int docNum = -1;

	public MemoryDocumentManager() {
		docMap = new MemoryMapData<IndexDocument>();
	}

	@Override
	public void addDocuments(IDocumentIterator docIter,
			ITextTokenizer tokenizer, boolean addToTree) {
		while (docIter.hasNext()) {
			this.docNum++;
			ITextDocument doc = docIter.next();
			doc.setDocID(this.docNum);
			IndexDocument indexDoc = new IndexDocument(doc, tokenizer);
			this.docMap.add(this.docNum, indexDoc);
			if (addToTree)
				Index.getTreeConstructor().addDocumentToSTree(indexDoc);
		}
	}

	@Override
	public IndexDocument getDocument(int docID) {
		if (this.docMap.containsKey(docID))
			return this.docMap.get(docID);
		else
			return null;
	}

	@Override
	public long numberOfDocuments() {
		return this.docNum + 1;
	}

	public void open(String path, String baseName) {
		docMap = new MemoryMapData<IndexDocument>();

		this.docMap.open(path, baseName + ".docManager.map");

		FileInputStream fis = null;
		ObjectInputStream in = null;

		try {
			fis = new FileInputStream(path + "/" + baseName
					+ ".docManager.size");
			in = new ObjectInputStream(fis);
			this.docNum = (Integer) in.readObject();
			in.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void save(String path, String baseName) {
		this.docMap.save(path, baseName + ".docManager.map");

		FileOutputStream fos = null;
		ObjectOutputStream out = null;

		try {
			fos = new FileOutputStream(path + "/" + baseName
					+ ".docManager.size");
			out = new ObjectOutputStream(fos);
			out.writeObject(this.docNum);
			out.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

}
